<!--created by yuyupeng-->
<!--2023/03/22-->
<!-- 数据字典详情-->
<template>
  <div>
    <!-- 查询表单 -->
    <AdvancedSearch
      ref="searchRef"
      :data-source="searchItemList"
      @change="searchByParams"
    />
    <a-space style="margin-top: 5px; margin-bottom: 5px">
      <a-button type="primary" @click="showAddModal"
        ><icon-plus />新增</a-button
      >
      <a-popconfirm
        content="确定删除吗?"
        type="warning"
        @ok="deleteTbDataList(selectedKeys)"
      >
        <a-button :disabled="selectedKeys.length === 0"
          ><icon-delete />批量删除</a-button
        >
      </a-popconfirm>
    </a-space>
    <!-- 表格 -->
    <a-table
      v-model:selectedKeys="selectedKeys"
      row-key="id"
      column-resizable
      :columns="tbCols"
      :data="tbData"
      :row-selection="rowSelection"
      :pagination="pagination"
      :loading="tbLoading"
      :scroll="{ x: '100%', y: 600 }"
      :scrollbar="true"
      @sorter-change="onSorterChange"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
    >
      <!-- 插槽-一键复制 -->
      <template #quickCopyToolTip="{ record, column }">
        <quick-copy-tool-tip
          :show-text="record[column['dataIndex']]"
          show-btn
        />
      </template>
      <!-- 插槽-操作 -->
      <template #operation="{ record }">
        <a-space>
          <a-link type="text" @click="showEditModal(record)"> 修改 </a-link>
          <a-popconfirm
            content="确定删除吗?"
            type="warning"
            @ok="deleteTbData(record.id)"
          >
            <a-link type="text">删除</a-link>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
    <!-- 新增数据字典详细信息弹窗 -->
    <AdvancedFormModal
      ref="addModalRef"
      width="600px"
      title="新增数据字典详细信息"
      :items="addModalConfig"
      :rules="advancedModalRules"
      @ok="addModalSubmit"
    />
    <!-- 修改数据字典详细信息弹窗 -->
    <AdvancedFormModal
      ref="editModalRef"
      width="600px"
      title="修改数据字典详细信息"
      :items="editModalConfig"
      :rules="advancedModalRules"
      @ok="editModalSubmit"
    />
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import {
    Notification,
    TableColumnData,
    TableRowSelection,
  } from '@arco-design/web-vue';
  import {
    DictDataParamsSort,
    DictDataRecord,
  } from '@/api/system/model/dictDataModel';
  import {
    queryDictDataRecordList,
    addDictDataRecord,
    editDictDataRecord,
    deleteDictDataRecords,
  } from '@/api/system/dictionary';
  import { ref, onMounted, toRefs, reactive } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedFormModal from '@/common/components/cac-components/advanced-form-modal/index.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';

  const props = defineProps({
    dictType: { type: String, required: true }, // 字典类型编码
  });

  /**
   * data
   */
  const {
    dictType, // 字典类型编码
  } = toRefs(props); // 根据props创建多个 ref 对象
  // 表格
  const tbData = ref<DictDataRecord[]>([]);
  const tbCols: TableColumnData[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    /* { title: '字典编码', dataIndex: 'id', fixed: 'left', ellipsis: true, align: 'center', tooltip: true },
    { title: '查看', fixed: 'left', align: 'center', width: 100, slotName: 'detail' }, */
    {
      title: '字典标签',
      dataIndex: 'label',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '字典键值',
      dataIndex: 'value',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '字典排序',
      dataIndex: 'sort',
      width: 150,
      align: 'center',
      ellipsis: true,
      // sortable: {
      //   // sortDirections: ['ascend', 'descend'],
      //   sortDirections: ['ascend'],
      //   sorter: true, // 使用后端排序的时候需要把前端的排序禁用，按照官网的说法设为true就是禁用
      // },
    },
    /* { title: '字典类型', dataIndex: 'dictType', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '状态（0正常 1停用）', dataIndex: 'status', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '备注', dataIndex: 'remark', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '所属部门ID(非必须)', dataIndex: 'deptId', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '所属组织机构ID(非必须)', dataIndex: 'orgId', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '创建者', dataIndex: 'creator', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '创建时间', dataIndex: 'createTime', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新者', dataIndex: 'updater', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新时间', dataIndex: 'updateTime', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新ip', dataIndex: 'updateIp', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '是否删除(非必须)', dataIndex: 'deleted', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', dataIndex: 'secretLevel', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '乐观锁', dataIndex: 'version', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' }, */
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 120,
      slotName: 'operation',
    },
  ];
  const orderField = ref<string>('sort'); // 排序字段
  const order = ref<string>('asc'); // 排序方式 分为asc升序 desc降序
  const searchRef = ref<any>();
  const addModalRef = ref<any>();
  const editModalRef = ref<any>();
  const currentRecord = ref<DictDataRecord>(); // 记录当前选择的表格行
  const tbLoading = ref<boolean>(false);
  // 勾选框
  const selectedKeys = ref([]);
  const rowSelection: TableRowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    { type: 'text', labelText: '字典标签', fieldName: 'label' },
    { type: 'text', labelText: '字典键值', fieldName: 'value' },
  ];
  // 新增弹窗配置项
  const addModalConfig = [
    {
      span: 24,
      type: 'text',
      labelText: '字典类型',
      fieldName: 'dictType',
      disabled: true,
    },
    { span: 24, type: 'text', labelText: '字典标签', fieldName: 'label' },
    { span: 24, type: 'text', labelText: '字典键值', fieldName: 'value' },
    {
      span: 24,
      type: 'number',
      labelText: '字典排序',
      fieldName: 'sort',
      min: 0,
    },
  ];
  // 修改弹窗配置项
  const editModalConfig = [
    {
      span: 24,
      type: 'text',
      labelText: 'id',
      fieldName: 'id',
      visible: false,
    },
    {
      span: 24,
      type: 'text',
      labelText: '字典类型',
      fieldName: 'dictType',
      disabled: true,
    },
    { span: 24, type: 'text', labelText: '字典标签', fieldName: 'label' },
    { span: 24, type: 'text', labelText: '字典键值', fieldName: 'value' },
    {
      span: 24,
      type: 'number',
      labelText: '字典排序',
      fieldName: 'sort',
      min: 0,
    },
  ];
  // 弹窗表单项校验配置
  const advancedModalRules = ref({
    label: [{ required: true, message: '请输入字典标签' }],
    value: [{ required: true, message: '请输入字典键值' }],
    sort: [{ required: true, message: '请输入字典排序' }],
  });
  /**
   * func
   */
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbData = async (reqdata: any = {}) => {
    const params: DictDataParamsSort = {
      ...reqdata,
      dictType: dictType.value, // 数据字典类型编码
      orderField: orderField.value, // 对sort字段进行排序
      order: order.value, // 排序方式，分为asc升序 desc降序
    };
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const { data } = await queryDictDataRecordList(params);
      tbData.value = data;
      pagination.total = data.length;
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    getTbData(reqdata);
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    // searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @description 排序发生变化触发
   * @param dataindex 排序的字段名字
   * @param direction 排序方向
   */
  const onSorterChange = (
    dataindex: string,
    direction: 'ascend' | 'descend'
  ) => {
    orderField.value = dataindex;
    order.value = direction === 'ascend' ? 'asc' : 'desc';
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    // searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 新增弹窗提交
   */
  const addModalSubmit = async (reqdata: any) => {
    try {
      const res = (await addDictDataRecord(reqdata)) as any;
      if (res.code === 200) {
        Notification.success({
          content: '保存成功！',
        });
      } else {
        Notification.error({
          title: '保存失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 修改弹窗提交
   */
  const editModalSubmit = async (reqdata: any) => {
    console.log(reqdata);
    try {
      const res = (await editDictDataRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 删除数据字典信息
   */
  const deleteTbData = async (id: string) => {
    const reqdata = [];
    reqdata.push(id);
    try {
      const res = (await deleteDictDataRecords(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 批量删除数据字典信息，传id数组，支持批量
   */
  const deleteTbDataList = async (ids: string[]) => {
    try {
      const res = (await deleteDictDataRecords(ids)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 打开新增弹窗
   */
  const showAddModal = () => {
    addModalRef.value.open({
      dictType: dictType.value,
      sort: 0,
    }); // 打开数据字典详情抽屉
  };
  /**
   * @description 打开修改弹窗
   * @param record 当前选择的表格行数据
   */
  const showEditModal = (record: DictDataRecord) => {
    currentRecord.value = record;
    editModalRef.value.open({
      id: record.id,
      dictType: dictType.value,
      label: record.label,
      value: record.value,
      sort: record.sort,
    }); // 打开修改弹窗
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTbData();
  });
</script>
